import { ArgumentsHost, Catch, ExceptionFilter, HttpException, LoggerService, UnauthorizedException } from '@nestjs/common'
import type { Response } from 'express'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private logger: LoggerService) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    // const request = ctx.getRequest<Request>()
    const response = ctx.getResponse<Response>()
    const status = exception.getStatus()
    const res = exception['response'] || exception
    // 判断res是否是字符串

    let message = typeof res === 'string' ? res : res.message
    if (exception instanceof UnauthorizedException) {
      message = message || '用户验证失败'
    }
    console.log('error', res)
    this.logger.error(message, exception.stack || '')
    response.status(status).json({
      status,
      data: null,
      message
    })
  }
}
